package departmentintro;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import com.andro.chansung.ConstantURL;
import com.andro.chansung.R;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

public class ProffesorAdapter extends BaseAdapter {

	private List<Proffesor> proffesors;
	private LayoutInflater inflater;
	private Activity activity;
	private ViewHolder viewHolder;
	private ImageHandler handler;
	private Drawable image;
	
	private class ViewHolder {
		public ImageView image;
		public TextView nameTv;
		public TextView degreeTv;
		public TextView majorTv;
		public TextView labTv;
		public TextView emailTv;
		public Button   phoneBtn;
	}
	
	public ProffesorAdapter(Activity activity, List<Proffesor> proffesors) {
		this.activity = activity;
		this.proffesors = proffesors;
		this.inflater = LayoutInflater.from(activity);
		handler = new ImageHandler();
	}
	
	public int getCount() {
		return proffesors.size();
	}

	public Proffesor getItem(int position) {
		return proffesors.get(position);
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		View view = convertView;
		
		if( view == null ) {
			viewHolder = new ViewHolder();
			view = inflater.inflate(R.layout.proffesor_intro_list_view_cell_layout, null);
			viewHolder.image = (ImageView)view.findViewById(R.id.proffesor_intro_list_view_cell_image);
			viewHolder.nameTv = (TextView)view.findViewById(R.id.proffesor_intro_list_view_cell_name_tv);
			viewHolder.degreeTv = (TextView)view.findViewById(R.id.proffesor_intro_list_view_cell_degree_tv);
			viewHolder.majorTv = (TextView)view.findViewById(R.id.proffesor_intro_list_view_cell_major_tv);
			viewHolder.labTv = (TextView)view.findViewById(R.id.proffesor_intro_list_view_cell_lab_tv);
			viewHolder.emailTv = (TextView)view.findViewById(R.id.proffesor_intro_list_view_cell_email_tv);
			viewHolder.phoneBtn = (Button)view.findViewById(R.id.proffesor_intro_list_view_cell_phone_btn);
			view.setTag(viewHolder);
		} else {
			viewHolder = (ViewHolder)view.getTag();
		}
		
		final Proffesor proffesor = getItem(position);
		Thread tmpThread = new Thread(new Runnable(){
			public void run() {
				image = ImageOperations(activity, ConstantURL.BASE_IMG_URL + proffesor.getImageUrlAdr(), "img/image_" + proffesor.getName() + ".jpg");
				handler.sendEmptyMessage(0);
			}
		});
		File imageFile = new File("img/image_" + proffesor.getName() + ".jpg");
		if( imageFile.exists() ) {
            Drawable d = Drawable.createFromPath(imageFile.getPath());
            viewHolder.image.setImageDrawable(d);
            Log.d("debug", "file exists!");
		} else {
			tmpThread.start();
		}
			
		viewHolder.nameTv.setText(proffesor.getName());
		viewHolder.degreeTv.setText(proffesor.getDegree());
		viewHolder.majorTv.setText(proffesor.getMajor());
		viewHolder.emailTv.setText(proffesor.getEmail());
		
		String tmpLabStr = proffesor.getLab();
		String[] labStrs = tmpLabStr.split("☎");
		viewHolder.labTv.setText(labStrs[0]);
		viewHolder.phoneBtn.setText(labStrs[1]);
		
		viewHolder.phoneBtn.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				Uri number = Uri.parse("tel:" + ((Button)v).getText());
				Intent dial = new Intent(Intent.ACTION_DIAL, number);
				activity.startActivity(dial);
			}
		});
		
		return view;
	}
	
	private class ImageHandler extends Handler {
		public void handleMessage(Message msg) {
			viewHolder.image.setImageDrawable(image);
		}
	}
	
	private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
        try {
            URL imageUrl = new URL(url);
            InputStream is = (InputStream) imageUrl.getContent();
            
            Drawable d = Drawable.createFromStream(is, "src");
            
//            File file = new File(saveFilename);
//            file.createNewFile();
//            FileOutputStream fos = new FileOutputStream(file);
//            Bitmap bm = Bitmap.createBitmap(d.getMinimumWidth(), d.getMinimumHeight(), Bitmap.Config.ARGB_8888);
//            bm.compress(CompressFormat.JPEG, 100, fos);
//            fos.flush();
//            fos.close();
            return d;
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}
